<template>
  <!-- 操作栏 -->
  <el-row justify="end">
    <el-button @click="openForm(contract.id)">
      <Icon class="mr-5px" icon="clarity:contract-line" />  添加产品
    </el-button>
<!--    <el-button @click="openForm(contract.id)">-->
<!--      <Icon class="mr-5px" icon="clarity:contract-line" /> 导入产品-->
<!--    </el-button>-->
  </el-row>
  <!-- 列表 align="center" -->
  <ContentWrap>
    <el-table :data="contract.products" :stripe="true" :show-overflow-tooltip="true" show-summary
              :cell-style="getRowClassName" :summary-method="getSummaries"
              :default-sort = "{prop: 'productNo', order: 'descending'}">
      <el-table-column label="序号" align="center" type="index" width="60" fixed="left"/>
      <el-table-column type="expand" >
        <template #default="scope">
          <el-tabs model-value="demo03Course">
            <el-tab-pane label="部件信息" name="demo03Course">
             <ContractItemList :product-id="scope.row.productId" :contract-id="contract.id" />
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="产品名称"
        fixed="left"
        prop="productName"
        min-width="160"
      >
        <template #default="scope">
          <el-link :underline="false" type="primary" @click="openDetail(scope.row.productId)">
             <span :style="{ color: getColor(scope.row.contractPrice) }">
               {{ scope.row.productName }}
             </span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="产品代码" align="center" prop="productNo" min-width="120" sortable>
        <template #default="scope">
          <span :style="{ color: getColor(scope.row.contractPrice) }">
               {{ scope.row.productNo }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属品牌" align="center" prop="brandName" min-width="120" />
<!--      <el-table-column align="center" label="产品单位" prop="productUnit" min-width="120">-->
<!--        <template #default="{ row }">-->
<!--          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="row.productUnit" />-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="产品价格（元）"  align="center"  prop="productPrice"  min-width="140"-->
<!--        :formatter="erpPriceTableColumnFormatter" />-->
      <el-table-column label="订单价格（元）"  align="center"  prop="contractPrice"  min-width="140"
        :formatter="erpPriceTableColumnFormatter" sortable/>
      <el-table-column  align="center" label="数量"  prop="count" min-width="80px"
                        :formatter="erpPriceTableColumnFormatter" sortable>
        <template #default="{ row }">
          {{row.count}}
          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="row.productUnit" />
        </template>
      </el-table-column>
      <el-table-column label="合计金额（元）"  align="center" prop="totalPrice"  min-width="140" sortable
                        :formatter="erpPriceTableColumnFormatter" />
      <el-table-column label="备注" align="center" prop="note" min-width="120" />
      <el-table-column v-if="contract.orderStatus === 10|| contract.orderStatus === 0" label="操作" align="center" fixed="right" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="editForm('update',scope.row.id)"
            v-hasPermi="['crm:product:update']"
          > 编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:product:update']"
          > 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    <el-table-->
<!--      :data="tableData"-->
<!--      border-->
<!--      height="200"-->
<!--      :summary-method="getSummaries"-->
<!--      show-summary-->
<!--      style="width: 100%; margin-top: 20px">-->
<!--      <el-table-column-->
<!--        prop="id"-->
<!--        label="ID"-->
<!--        width="180">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="name"-->
<!--        label="姓名">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="amount1"-->
<!--        label="数值 1（元）">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="amount2"-->
<!--        label="数值 2（元）">-->
<!--      </el-table-column>-->
<!--      <el-table-column-->
<!--        prop="amount3"-->
<!--        label="数值 3（元）">-->
<!--      </el-table-column>-->
<!--    </el-table>-->
    <el-row class="mt-10px" justify="end">
<!--      <el-col :span="3"> 整单折扣：{{ erpPriceInputFormatter(contract.discountPercent) }}% </el-col>-->
      <el-col :span="4">
        产品总金额：{{ erpPriceInputFormatter(contract.totalProductPrice) }} 元
      </el-col>
    </el-row>
  </ContentWrap>
  <!-- 表单弹窗：添加 -->
  <ContractProductDetailForm ref="formRef" @success="forceRerender" />
</template>
<script setup lang="ts">
import * as ContractApi from '@/api/crm/contract'
import ContractProductDetailForm from './ContractProductDetailForm.vue'
import ContractItemList from './ContractItemList.vue'
import { erpPriceInputFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { DICT_TYPE } from '@/utils/dict'
import { useRouter } from 'vue-router';
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 加载中
const total = ref(0) // 列表的总页数
const { contract } = defineProps<{
  contract: ContractApi.ContractVO
}>()
// total.value = data.total
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined as unknown // 允许 undefined + number
})

const router = useRouter();
const forceRerender = () => {
  router.go(0);

};
/** 添加 */
const formRef = ref()
const openForm = (contractId?: number) => {
  formRef.value.open('create',null,contractId)
}
const editForm = (type: string, id?: number) => {
  formRef.value.open('update',id,null)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractApi.deleteContractProduct(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await forceRerender()
  } catch {
    message.error('删除操作失败，请您重新操作！')
  }
}
const  getColor = (contractPrice)=>{
  if(!contractPrice){
    return "#FFB009";
  }else{
    return "";
  }
}
const getRowClassName = (row,column,rowIndex,columnIndex) => {
  if (!row.brandName ) {
    return {background:'active-row'};
  } else{
    return {background:'inactive-row',color:'red'};
  }
  return ''; // 默认返回空字符串，不应用任何额外类名
};
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if(index!=6&&index!=7){
      return;
    }
    let unitName = ' '
    if(index===6){
      unitName = ' 套'
    }else if(index===7){
      unitName = ' 元'
    }

    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return (prev + curr);
        } else {
          return (prev);
        }
      }, 0);
      sums[index] = erpPriceInputFormatter(sums[index])
      sums[index] += unitName;
    } else {
      sums[index] = 'N/A';
    }
  });

  return sums;
};
/** 打开详情 */
const { currentRoute, push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'CrmProductDetail', params: { id } })
}
</script>
<style>
.active-row {
  background-color: #e2f0d9; /* 活跃状态的背景颜色 */
}
.inactive-row {
  background-color: #f5d9d9; /* 非活跃状态的背景颜色 */
}
</style>
